package com.zoe.onelink.business.ws;

import com.sun.tools.javac.file.CacheFSInfo;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
import org.apache.cxf.common.util.Compiler;
import org.springframework.boot.loader.LaunchedURLClassLoader;
import org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedWebappClassLoader;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Arrays;
import java.util.Locale;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2023</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2023-02-14
 */
public class OnelinkCxfCompile extends Compiler {

    @Override
    protected boolean useJava6Compiler(String[] files) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            throw new IllegalStateException(
                    "No compiler detected, make sure you are running on top of a JDK instead of a JRE.");
        }
        Context context = new Context();
        context.put(Locale.class, (Context.Factory<Locale>) null);
        PrintWriter pw = new PrintWriter(System.err, true);
        context.put(Log.errKey, pw);
        CacheFSInfo.preRegister(context);
        LaunchedURLClassLoader launchedURLClassLoader;
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL[] urls;
        if (classLoader instanceof TomcatEmbeddedWebappClassLoader) {
            ClassLoader parent = classLoader.getParent();
            urls = parent instanceof LaunchedURLClassLoader
                    ? ((LaunchedURLClassLoader) parent).getURLs()
                    : ((TomcatEmbeddedWebappClassLoader) classLoader).getURLs();
        } else {
            urls = ((LaunchedURLClassLoader) classLoader).getURLs();
        }
        LaunchedURLClassLoader loader = new LaunchedURLClassLoader(urls, classLoader);
        OnelinkJarFileManager fileManager = new OnelinkJarFileManager(loader, context);
        Iterable<? extends JavaFileObject> fileList = fileManager.getJavaFileObjectsFromStrings(Arrays
                .asList(files));
        return internalJava6Compile(compiler, wrapJavaFileManager(fileManager), setupDiagnosticListener(),
                fileList);
    }


}
